package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        //1 参数校验判断手机号和密码是否为空
        if (Strings.isNotBlank(dto.getPhone())&&Strings.isNotBlank(dto.getPassword())) {
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"请检查手机号！！！");
            }
            String salt = apUser.getSalt();
            String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if (!apUser.getPassword().equals(pwd)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号或密码错误！！！");
            }
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            apUser.setPassword("");
            apUser.setSalt("");
            apUser.setPhone("");
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);

        }else {
            //2 手机号和密码为空则使用设备id校验登陆登陆
            if (dto.getEquipmentId()==null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"未查询设备信息");
            }
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);

        }
    }
}
